package com.dongbo.recorder.screenrecord.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dongbo.recorder.screenrecord.AppLpds;
import com.dongbo.recorder.screenrecord.Constants;
import com.dongbo.recorder.screenrecord.LoadAd;
import com.dongbo.recorder.screenrecord.R;
import com.dongbo.recorder.screenrecord.base.BaseActivity;
import com.dongbo.recorder.screenrecord.bean.NetResponse;
import com.dongbo.recorder.screenrecord.bean.UserBean;
import com.dongbo.recorder.screenrecord.bean.WXInfo;
import com.dongbo.recorder.screenrecord.prefrences.PreferencesRepository;
import com.dongbo.recorder.screenrecord.utils.CodeCount;
import com.dongbo.recorder.screenrecord.utils.DialogUtils;
import com.dongbo.recorder.screenrecord.utils.TextValidator;
import com.dongbo.recorder.screenrecord.wxapi.WXEntryActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.leefeng.promptlibrary.PromptDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Description:
 * @Author: gstory0404@gmail
 * @CreateDate: 2020/5/6 14:28
 */
public class LoginActivity extends BaseActivity {

    @BindView(R.id.login_back)
    ImageView loginBack;
    @BindView(R.id.login_phone_input)
    EditText loginPhoneInput;
    @BindView(R.id.login_psd_input)
    EditText loginPsdInput;
    @BindView(R.id.login_getcode)
    TextView loginGetcode;
    @BindView(R.id.login_btn)
    Button loginBtn;
    @BindView(R.id.login_weixin)
    ImageView loginWeixin;
    @BindView(R.id.first_agree)
    ImageView firstAgree;


    private boolean isAgree = false;
    public static String WX_LOGIN_ACTION = "WX_LOGIN_ACTION";
    public static String WX_LOGIN_CODE = "WX_LOGIN_CODE";

    private String login_again = "";
    private CodeCount codeCount;
    private WXInfo mWXInfo;
    private WXLoginReceiver receiver;

    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this).statusBarDarkFont(false).init();
        //登录超时 未知返回
//        Bundle bundle = getIntent().getExtras();
//        if (bundle != null) {
//            login_again = bundle.getString("login_again");
//        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WX_LOGIN_ACTION);
        receiver = new WXLoginReceiver();
        registerReceiver(receiver, intentFilter);
        checkAgree();

        FrameLayout mExpressContainer = findViewById(R.id.express_container);
        new LoadAd().initTTSDKConfig(this, Constants.ADV_BANNER_ID, new LoadAd.OnAdEventListener() {
            @Override
            public void removeAllViews() {
                mExpressContainer.removeAllViews();
            }

            @Override
            public void onLoadError(int code, String message) {
                mExpressContainer.removeAllViews();
            }

            @Override
            public void addAllViews(View view, float width, float height) {
                mExpressContainer.removeAllViews();
                mExpressContainer.addView(view);
            }

            @Override
            public void closeAd(int position, String value, boolean enforce) {
                mExpressContainer.removeAllViews();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    private void checkAgree() {
        if (isAgree) {
            firstAgree.setImageResource(R.mipmap.icon_choose);
        } else {
            firstAgree.setImageResource(R.mipmap.icon_uns);
        }
    }

    @OnClick({R.id.login_back,
            R.id.login_getcode,
            R.id.login_btn,
            R.id.login_weixin,
            R.id.tv_user_agreement,
            R.id.tv_privacy_policy,
            R.id.first_agree})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_back:
                hideSoftInput();
                finish();
                break;
            case R.id.login_getcode:
                requestVerifyCode();
                break;
            case R.id.login_btn:
                if (!isAgree) {
//                    showToast(getResources().getString(R.string.tips_agreement));
                    DialogUtils.initDialog(LoginActivity.this, new DialogUtils.LoginDialog() {
                        @Override
                        public void loginDialog() {
                            requestVerifyCode();
                        }
                    });
                    return;
                }
//                requestVerifyCode();
                loginByCode();
                break;
            case R.id.login_weixin:
                if (!isAgree) {
//                    showToast(getResources().getString(R.string.tips_agreement));
                    DialogUtils.initDialog(LoginActivity.this, new DialogUtils.LoginDialog() {
                        @Override
                        public void loginDialog() {
                            logWx();
                        }
                    });
                    return;
                }
                logWx();
                break;
            case R.id.tv_user_agreement://用户协议
                WebActivity.start(LoginActivity.this,
                        "用户协议",
                        Constants.FUWU);
                break;
            case R.id.tv_privacy_policy://隐私政策
                WebActivity.start(LoginActivity.this,
                        "隐私政策",
                        Constants.YINSI);
                break;
            case R.id.first_agree:
                isAgree = !isAgree;
                checkAgree();
                break;
        }
    }

    private void logWx() {
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID, false);
        api.registerApp(Constants.WX_APP_ID);
        if (!api.isWXAppInstalled()) {
            Toast.makeText(LoginActivity.this, "请先安装微信客户端", Toast.LENGTH_SHORT).show();
            return;
        } else {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo_lpds";//请求标识  wechat_sdk_demo_test
            api.sendReq(req);
        }
    }

    //请求验证码
//    public void requestCode() {
//        if (TextUtils.isEmpty(getPhone())) {
//            showToast(getString(R.string.input_phone));
//            return;
//        }
//
//        if (!(getPhone().length() == 11)) {
//            showToast(getString(R.string.phone_pattern_hint));
//            return;
//        }
//        String token = Constants.SIGN_KEY + "app/member/u/sendSms";
//        String sign = MD5.getMessageDigest(token);
//        RequestBody body = new FormBody.Builder()
//                .add("account", getPhone())
//                .add("appexpId", Constants.APPEXP_ID)
//                .add("type", "3")
//                .add("sign", sign != null ? sign : "")
//                .build();
//        OkHttpClient okHttpClient = new OkHttpClient();
//        final Request request = new Request.Builder()
//                .url(Constants.BASE_URL + "app/member/u/sendSms")
//                .post(body)//默认就是GET请求，可以不写
//                .build();
//        Call call = okHttpClient.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                runOnUiThread(() -> {
//                    showToast(e.getMessage());
//                    if (loginGetcode != null) {
//                        loginGetcode.setEnabled(true);
//                        loginGetcode.setText("重新发送");
//                        loginGetcode.setTextColor(getResources().getColor(R.color.color_main));
//                    }
//                });
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                //得到返回的验证码
//                String body = response.body().string();
//                String data = DecryptOrNullBack.judgeError(body);
//                BaseModel<String> info = null;
//                try {
//                    info = new Gson().fromJson(data, BaseModel.class);
//                    if (info != null
//                            && info.isSuccess()
//                            && info.getStatusCode() == 1) {
//                        runOnUiThread(() -> {
//                            showToast("发送成功");
//                            onVerifyCodeSent("");
//                            countDown();
//                        });
//                    } else {
//                        BaseModel finalInfo = info;
//                        runOnUiThread(() -> {
//                            showToast(finalInfo.getMessage());
//                            if (loginGetcode != null) {
//                                loginGetcode.setEnabled(true);
//                                loginGetcode.setText("重新发送");
//                                loginGetcode.setTextColor(getResources().getColor(R.color.color_main));
//                            }
//                        });
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//
//    }

    public void requestVerifyCode() {
        if (TextUtils.isEmpty(getPhone())) {
            showToast(getString(R.string.input_phone));
            return;
        }
        if (!TextValidator.isMobilePhone(getPhone())) {
            showToast(getString(R.string.phone_pattern_hint));
            return;
        }

        RequestBody body = new FormBody.Builder()
                .add("account", getPhone())
//                .add("appexpId", Constants.APP_ID)
//                .add("type", "3")
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .addHeader("Authorization", AppLpds.getInstance().getToken())
                .url(Constants.BASE_URL + "/api/user/sendSms?phone=" + getPhone())
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> showToast(e.getMessage()));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //得到返回的验证码
                String json = response.body().string();
//                Tt.show(LoginActivity.this, json);
                if (!TextUtils.isEmpty(json)) {
                    runOnUiThread(() -> {
//                        byte[] bytes = Base64.decode(data);
//                        if (null != bytes && bytes.length > 0) {
//                            String json = new String(bytes);
                        JSONObject jsonObject = null;
                        Log.i("dddd", "===" + json);
                        int code = 0;
                        try {
                            jsonObject = new JSONObject(json);
                            code = jsonObject.getInt("code");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (code == 200) {
                            onVerifyCodeSent("");
                            countDown();
                        }
//                        }
                    });
                }
            }
        });

    }

    /*
     * 验证验证码
     * */
//    public void requestVerifyCode() {
//        if (TextUtils.isEmpty(getPhone())) {
//            showToast(getString(R.string.input_phone));
//            return;
//        }
//        if (!(getPhone().length() == 11)) {
//            showToast(getString(R.string.phone_pattern_hint));
//            return;
//        }
//        if (TextUtils.isEmpty(getVerifyCode())) {
//            showToast(getString(R.string.hint_psd));
//            return;
//        }
//
//        RequestBody body = new FormBody.Builder()
//                .add("account", getPhone())
//                .add("code", getVerifyCode())
//                .add("type", "3")
//                .build();
//        OkHttpClient okHttpClient = new OkHttpClient();
//        Request request = new Request.Builder()
//                .url(Constants.BASE_URL + "app/member/u/validCode")
//                .post(body)//默认就是GET请求，可以不写
//                .build();
//        Call call = okHttpClient.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                runOnUiThread(() -> {
//                    showToast(e.getMessage());
//                });
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String body = response.body().string();
//                String data = DecryptOrNullBack.judgeError(body);
////                Log.i("TAG__oo", data);
//                BaseModel info = null;
//                try {
//                    info = new Gson().fromJson(data, BaseModel.class);
//                    if (info != null
//                            && info.isSuccess()
//                            && info.getStatusCode() == 1) {
//                        runOnUiThread(() -> {
//                            loginByCode();
//                        });
//                    } else {
//                        BaseModel finalInfo = info;
//                        runOnUiThread(() -> {
//                            showToast(finalInfo.getMessage());
//                        });
////                        Tt.show(LoginActivity.this, info.getMessage());
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//
//    }

    private void loginByCode() {
        PromptDialog promptDialog = new PromptDialog(this);
        promptDialog.showLoading("正在登录");
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("phone", getPhone())
                .add("code", getVerifyCode())
                .add("brand", android.os.Build.BRAND)
                .add("release", android.os.Build.VERSION.RELEASE)
                .add("appId", Constants.APP_ID)
                .build();
        final Request request = new Request.Builder()
                .url(Constants.BASE_URL + "/api/user/phoneLogin")
                .addHeader("Authorization", AppLpds.getInstance().getToken())
                .post(body)//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    promptDialog.dismiss();
                    showToast(e.getMessage());
//                    SysAlertDialog.cancelLoadingDialog();
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                runOnUiThread(() -> {
//                    SysAlertDialog.cancelLoadingDialog();
                    promptDialog.dismiss();
                });
                String json = response.body().string();
                if (TextUtils.isEmpty(json)) {
                    return;
                }
                runOnUiThread(() -> {
//                    String json;
//                    byte[] bytes = Base64.decode(body);
//                    if (null != bytes && bytes.length > 0) {

                    Log.i("ddd", json);

                    NetResponse<UserBean> info = new Gson().fromJson(json, new TypeToken<NetResponse<UserBean>>() {
                    }.getType());
                    if (null == info) {
                        return;
                    }
                    if (info.getStatusCode() == 200 && info.getData() != null) {
                        Log.i("ddd", json);
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_DATA, new Gson().toJson(info.getData()));
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_TOKEN, info.getToken());
                        AppLpds.getMySp().setUserInfo(info.getData());
                        onLoginSuccess();
                    } else {
                        Log.i("ddd", "登录失败");
                    }
//                    }
                });
            }
        });

    }


    public void onLoginSuccess() {
        finish();
    }


    private void loginByWX(String code) {
//        WXInfo mWXInfo = new WXInfo();
//        try {
//            mWXInfo = new Gson().fromJson(code, WXInfo.class);
//        } catch (IllegalStateException e) {
////            e.printStackTrace();
//            showToast("登录失败，请重试");
//            return;
//        }
//        if (mWXInfo == null) {
//            showToast("登录失败，请重试");
//            return;
//        }

        PromptDialog promptDialog = new PromptDialog(this);
        promptDialog.showLoading("正在登录...");
        Log.i("loginloginByWXByWX", "code=====" + code);
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("appId", Constants.APP_ID)
                .add("authCode", code)
                .add("loginType", "0")
                .add("brand", android.os.Build.BRAND)
                .add("release", android.os.Build.VERSION.RELEASE)
                //                .add("facilityName", Applmpl.getInstance().getDeviceName())
//                .add("facilityId", Applmpl.getInstance().getDeviceNo())
//                .add("openId", mWXInfo.getOpenid())
//                .add("nickname", mWXInfo.getNickname())
//                .add("avatar", mWXInfo.getHeadimgurl())
//                .add("pmentType", "ANDROID")
                .build();

        Map<String, Object> map = new HashMap<>();
        map.put("appId", Constants.APP_ID);
        map.put("authCode", code);
        map.put("loginType", 0);

        Request request = new Request.Builder()
                .url(Constants.BASE_URL + "/api/user/wxLogin")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    showToast(e.getMessage());
                    onSocialLoginCallBack();
                    promptDialog.dismiss();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                runOnUiThread(() -> {
//                    SysAlertDialog.cancelLoadingDialog();
                    promptDialog.dismiss();
                });
                String json = response.body().string();
                Log.i("ddd", "body===" + json);
                if (TextUtils.isEmpty(json)) {
                    return;
                }
//                byte[] bytes = Base64.decode(body);
//                String json;
//                if (null != bytes && bytes.length > 0) {
//                    json = new String(bytes);
//                    if (TextUtils.isEmpty(json)) {
//                        return;
//                    }

//                Log.i("ddd", "ddd===" + json);
                NetResponse<UserBean> info = new Gson().fromJson(json, new TypeToken<NetResponse<UserBean>>() {
                }.getType());
                runOnUiThread(() -> {
                    //登录成功，保存用户信息
                    if (null != info && info.getStatusCode() == 200 && info.getData() != null) {
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_DATA, new Gson().toJson(info.getData()));
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_TOKEN, info.getToken());
                        AppLpds.getMySp().setUserInfo(info.getData());
                        onLoginSuccess();
                    }
                    onSocialLoginCallBack();
                });
            }
        });

    }

    public void onSocialLoginCallBack() {
        sendBroadcast(new Intent(WXEntryActivity.WX_LOGIN_FAILED));
    }

    class WXLoginReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (WX_LOGIN_ACTION.equals(intent.getAction())) {
                loginByWX(intent.getStringExtra(LoginActivity.WX_LOGIN_CODE));
            }
        }
    }

    public void onVerifyCodeSent(String code) {
//        mSmsCode = code;
        loginPsdInput.setText("");
        loginPsdInput.setHint(getString(R.string.text_code));
    }

    //开始倒计时
    private void countDown() {
        loginGetcode.setEnabled(false);
        loginGetcode.setTextColor(getResources().getColor(R.color.color_unchoose));

        if (codeCount == null) {
            codeCount = new CodeCount(60000, 1000, loginGetcode);
        }
        codeCount.start();
    }

    public String getPhone() {
        return loginPhoneInput.getText().toString().trim();
    }


    public String getVerifyCode() {
        return loginPsdInput.getText().toString().trim();
    }

    public void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) AppLpds.getInstance().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.hideSoftInputFromWindow(loginPsdInput.getWindowToken(), 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }
}
